package leetcode.code1414;

import leetcode.IDebug;
import leetcode.helper.HelpDebug;


//执行用时：0 ms, 在所有 Java 提交中击败了100.00%的用户
//
//内存消耗：38.3 MB, 在所有 Java 提交中击败了5.15%的用户
//
//通过测试用例：504 / 504

public class Solution implements IDebug {

	static int[] fib;// fib放一起待用
	static int limit = 45;
	static {
		fib = new int[limit];
		fib[0] = 1;
		fib[1] = 1;
		for (int i = 2; i < 45; i++) {
			fib[i] = fib[i - 1] + fib[i - 2];
		}
	}

	public int findMinFibonacciNumbers(int k) {
		// findMinFibonacciNumbers(要找的数,右界,找到几个)
		return this.findMinFibonacciNumbers(k, limit, 0);
	}

	private int findMinFibonacciNumbers(int k, int limit, int ans) {
//		if (k == 0) {
//			return ans;
//		}
		int l = 0, r = limit;
		int close = 0;
		int M = 0;
		while (l <= r) {
			int m = ((r - l) >> 1) + l;
			if ((M = fib[m]) == k) {
				return ans + 1;
			} else if (M > k) {
				r = m - 1;
			} else {
				close = M;
				l = m + 1;
			}
		}
		return this.findMinFibonacciNumbers(k - close, r, ans + 1);
	}

	@Override
	public void debug1() {
		HelpDebug.compare(2, this.findMinFibonacciNumbers(7));
	}

	@Override
	public void debug2() {
		HelpDebug.compare(2, this.findMinFibonacciNumbers(10));
	}

	@Override
	public void debug3() {
		HelpDebug.compare(3, this.findMinFibonacciNumbers(19));
	}

	@Override
	public void debug4() {
		// TODO Auto-generated method stub

	}

	public static void main(String[] args) {
		Solution so = new Solution();
		so.debug1();
		so.debug2();
		so.debug3();
		so.debug4();
	}

}
